package org.fessingapore.library.daos.impl;

import java.sql.SQLException;
import java.util.List;

import org.fessingapore.library.daos.ItemDao;
import org.fessingapore.library.models.Item;
import org.fessingapore.library.models.Item;
import org.fessingapore.library.util.HibernateUtil;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

public class ItemDaoImpl extends GenericDaoImpl<Item, Integer> implements ItemDao{

	private Session session;
	
	public List<Item> search(Item item) throws SQLException {
		session = HibernateUtil.getSessionFactory().openSession();
        Criteria criteria = session.createCriteria(Item.class, "item");
        
        if (item.getAuthor() != null && !item.getAuthor().equals("")){
        	criteria.add(Restrictions.like("item.author", "%"+item.getAuthor()+"%"));
        }
        
        if (item.getIsbn() != null && !item.getIsbn().equals("")){
        	criteria.add(Restrictions.like("item.isbn", "%"+item.getIsbn()+"%"));
        }
        
        if (item.getCategories() != null && !item.getCategories().isEmpty()){
        	criteria.createAlias("item.categories", "category")
        	.add(Restrictions.eq("category.id", item.getCategories().get(0).getId()));
        }
        
        if (item.getLanguage() != null){
        	criteria.add(Restrictions.eq("item.language", item.getLanguage()));
        }
        
        if (item.getTitle() != null && !item.getTitle().equals("")){
        	criteria.add(Restrictions.like("item.title", "%"+item.getTitle()+"%"));
        }
        
        if (item.getPublisher() != null && !item.getPublisher().equals("")){
        	criteria.add(Restrictions.like("item.publisher", "%"+item.getPublisher()+"%"));
        }
        
        if (item.getType()!=null){
            criteria.add(Restrictions.eq("item.type", item.getType()));
        }
 
        List<Item> itemList = criteria.list();
        clear();
        return itemList;
	}


}
